package com.example.cloud.util.web;

import javax.servlet.http.HttpServletRequest;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * 请求相关的工具类
 *
 * @author tongyufu
 */
public class ActionUtils {

    /**
     * Spring MVC获取request的三种方法： <a href=
     * "http://yeelor.iteye.com/blog/1554795">http://yeelor.iteye.com/blog/1554795</a>
     *
     * @return HttpServletRequest
     */
    public static HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }

    /**
     * 获取请求的IP
     *
     * @return IP
     */
    public static String getIP() {
        HttpServletRequest request = ActionUtils.getRequest();
        String addr = request.getRemoteAddr();
        //haproxy代理后把真实访问ip放在http header的 “X-Forwarded-For”中
        String headerXForwardedFor = request.getHeader("X-Forwarded-For");
        return headerXForwardedFor == null ? addr : headerXForwardedFor;
    }

    /**
     * 获取服务器真实路径
     *
     * @param path 服务器路径
     * @return 真实路径
     */
    public static String getRealPath(String path) {
        HttpServletRequest request = ActionUtils.getRequest();
        return request.getSession().getServletContext().getRealPath(path);
    }
}
